/**
    Copyright (C) 2011  Alexander Vollmer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jefb.web.controller;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.jefb.entity.LinkEntity;
import org.jefb.entity.UserEntity;
import org.jefb.service.ICommonPersistenceService;
import org.jefb.service.IUserService;
import org.jefb.service.IUserSessionService;
import org.jefb.util.JefbUtils;
import org.jefb.web.model.DirectoryMananagerModel;
import org.jefb.web.model.FileDataHolder;
import org.jefb.web.model.LinkModel;
import org.jefb.web.util.Icons;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.DropEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Panel;

@org.springframework.stereotype.Component
@Scope("prototype")
public class LinkController extends GenericForwardComposer implements
		Serializable, ListitemRenderer {

	private static final long serialVersionUID = 1L;

	// UI components
	protected Listbox linkListbox;
	
	//models
	@Autowired
	private DirectoryMananagerModel directoryManagerModel;
	@Autowired
	private LinkModel linkModel;
	@Autowired
	private IUserSessionService userSessionService;
	
	//services
	@Autowired
	private ICommonPersistenceService commonPersistenceService;
	@Autowired
	private IUserService userService;

	public LinkController() {}

	public void init() {

	}

	public void onSelect$linkListbox(Event event) {
		LinkEntity selectedEntity = linkModel.getSelectedEntity();
		if (selectedEntity != null) {
			if (selectedEntity.getFile()) {
				directoryManagerModel.setCurrentDir(
						selectedEntity.getRelativePath(), NavAction.FORWARD);
			} else {
				directoryManagerModel.setCurrentDir(
						selectedEntity.getRelativeFile(), NavAction.FORWARD);
			}
		}
	}

	public void reloadList() {
		if (userSessionService.getUserEntity() != null) {
			List<LinkEntity> entities = new ArrayList<LinkEntity>();
			
			//Collection<LinkEntity> links = userService.getShortcuts(userSessionService.getUserEntity());
			Collection<LinkEntity> links = userSessionService.getUserEntity().getShortcuts();
			entities.addAll(links);
			if (linkModel.getListModel() != null) {
				linkModel.getListModel().clear();
				linkModel.getListModel().addAll(entities);
			} else {
				linkModel.setListModel(new BindingListModelList(entities,
						false));
			}
		}
		linkModel.setSelectedEntity(null);
	}

	public void doBeforeComposeChildren(Component comp) {
		reloadList();

		try {
			super.doBeforeComposeChildren(comp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		comp.addEventListener(Events.ON_DROP, new FileListDropEventListener());
		reloadList();
	}

	private class FileListDropEventListener implements EventListener {
		public void onEvent(Event event) throws Exception {
			if (event instanceof DropEvent) {
				DropEvent dropEvent = (DropEvent) event;
				Component component = dropEvent.getTarget();
				if (component instanceof Panel) {
					Listitem draggedListItem = (Listitem) dropEvent
							.getDragged();
					final FileDataHolder draggedFileHolder = (FileDataHolder) draggedListItem
							.getAttribute("fileDataHolder");
					File file = draggedFileHolder.getFile();

					LinkEntity newLinkEntity = new LinkEntity();
					newLinkEntity.setFile(file.isFile());
					newLinkEntity.setFilename(file.getName());
					String relativePath = JefbUtils.extractRelativePath(
							file.getParent(), userSessionService.getHomeDir());
					newLinkEntity.setRelativePath(relativePath);
					UserEntity userEntity = userSessionService.getUserEntity();
					if (!userEntity.getShortcuts().contains(newLinkEntity)) {
						userEntity.getShortcuts().add(newLinkEntity);
						commonPersistenceService.updateEntity(userEntity);
						//getUserService().addShortcut(userEntity, newLinkEntity);
						reloadList();
					}
				}
			}
		}
	}

	public void setDirectoryManagerModel(
			DirectoryMananagerModel directoryManagerModel) {
		this.directoryManagerModel = directoryManagerModel;
	}

	public DirectoryMananagerModel getDirectoryManagerModel() {
		return directoryManagerModel;
	}

	public void setUserSession(IUserSessionService userSessionService) {
		this.userSessionService = userSessionService;
	}

	public IUserSessionService getUserSession() {
		return userSessionService;
	}

	public void setCommonPersistenceService(
			ICommonPersistenceService commonPersistenceService) {
		this.commonPersistenceService = commonPersistenceService;
	}

	public ICommonPersistenceService getCommonPersistenceService() {
		return commonPersistenceService;
	}

	public void setShortcutModel(LinkModel linkModel) {
		this.linkModel = linkModel;
	}

	public LinkModel getShortcutModel() {
		return linkModel;
	}

	public void onClick$removeLinkButton(Event event) {
		LinkEntity selectedEntity = linkModel.getSelectedEntity();
		if (selectedEntity != null) {
			//userService.deleteShortcut(userSessionService.getUserEntity(), selectedEntity);
			userSessionService.getUserEntity().getShortcuts().remove(selectedEntity);
			commonPersistenceService.updateEntity(userSessionService.getUserEntity());
			reloadList();
		}
	}

	public void render(Listitem li, Object data) throws Exception {
		if (data instanceof LinkEntity) {
			final LinkEntity link = (LinkEntity) data;
			Listcell linkNameCell = new Listcell(link.getFilename());
			linkNameCell.setParent(li);
			linkNameCell.setTooltiptext(link.getRelativePath()
					+ JefbUtils.FILE_SEPARATOR + link.getFilename());
			if (link.getFile()) {
				linkNameCell.setImage("../img/fs16/"
						+ Icons.getSrc(link.getFilename()));
			} else {
				linkNameCell.setImage("../img/fs16/folder.png");
			}
		}

	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public IUserService getUserService() {
		return userService;
	}

}
